#include "QtGuiEx/ColorSelectorToolButton.qth"
#include "QtGuiEx/ColorSelectorToolButton.moh"
#include "QtGuiEx/ColorPaletteWidget.qth"
#include <QtGui/QPixmap>
#include <QtGui/QPainter>


namespace QtGuiEx
{

ColorSelectorToolButton::ColorSelectorToolButton( const QColor& defaultColor, QWidget* pParent)
	: QToolButton( pParent)
	, defaultColor_( defaultColor)
{
	this->setDefaultColor( defaultColor);
	this->setPopupMode( QToolButton::MenuButtonPopup);
	pColorPaletteWidget_ = new ColorPaletteWidget();
	this->setMenu( pColorPaletteWidget_);
	connect( pColorPaletteWidget_, SIGNAL( colorSelected( const QColor&)), this, SLOT( handleColorSelected( const QColor&)));
	connect( this, SIGNAL( clicked( bool)), this, SLOT( handleClicked( bool)));
}

// ---------------------------------------------------------------------------------------------------------------------

void ColorSelectorToolButton::handleColorSelected( const QColor& selectedColor)
{
	this->setDefaultColor( selectedColor);
	Q_EMIT colorSelected( selectedColor);
}

// ---------------------------------------------------------------------------------------------------------------------

void ColorSelectorToolButton::setDefaultColor( const QColor& newColor)
{
	defaultColor_ = newColor;
	
	QPixmap pixmap = this->icon().pixmap( QSize(16, 16), QIcon::Normal);

	QPainter painter;
	painter.begin( &pixmap);
	QRect rect( 0, 12, 16, 4);
	if( defaultColor_.isValid())
	{
		painter.fillRect( rect, QBrush( defaultColor_));
	}
	else
	{
		QColor fillColor( 255, 255, 255, 255);
		QColor borderColor( 0, 0, 0);
		painter.setPen( borderColor);
		painter.setBrush( fillColor);
		painter.drawRect( rect);
	}
	painter.end();

	this->setIcon( QIcon( pixmap));
}

// ---------------------------------------------------------------------------------------------------------------------

void ColorSelectorToolButton::handleClicked( bool)
{
	Q_EMIT colorSelected( this->defaultColor());
}

} // namespace QtGuiEx
